//
//  QuanlitySeartchViewController.m
//  MyProject
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "QuanlitySeartchViewController.h"
#import "QuanlityViewController.h"
#import "Topic.h"
#import "TopicTableViewCell.h"
#import "HandleData.h"
#import <UIImageView+WebCache.h>
@interface QuanlitySeartchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *listArr;
@property (nonatomic, strong) NSString *keyword;
@property (nonatomic, strong) UILabel *nothing;
@property (nonatomic, strong) UILabel *prompt;



@end

@implementation QuanlitySeartchViewController

- (void)viewWillAppear:(BOOL)animated
{
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
        self.tableView.backgroundColor = [UIColor grayColor];
        self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
        self.nothing.textColor = [UIColor whiteColor];
        self.prompt.textColor = [UIColor whiteColor];
    }else
    {
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.navigationController.navigationBar.barTintColor = [UIColor redColor];
        self.nothing.textColor = [UIColor redColor];
        self.prompt.textColor = [UIColor redColor];
        
    }
    
    
    [self.tableView reloadData];
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tabBarController.tabBar.hidden = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(backAction:)];
    
    UISearchBar *search = [[UISearchBar alloc] init];
    search.placeholder = @"请输入主题关键字";
    search.delegate = self;
    
    self.navigationItem.titleView = search;
    [search becomeFirstResponder];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
//    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    
//    NSString *nightPath = [docPath stringByAppendingPathComponent:@"night.txt"];
//    
//    NSString *nl = [NSString stringWithContentsOfFile:nightPath encoding:NSUTF8StringEncoding error:nil];
//    if ([nl isEqualToString:@"night"]) {
//        _tableView.backgroundColor = [UIColor blueColor];
//        
//    }else{
//        _tableView.backgroundColor = [UIColor whiteColor];
//    }
//    
    [self.view addSubview:self.tableView];
    
    self.nothing = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, self.view.bounds.size.width, 50)];
    _nothing.textColor = [UIColor colorWithRed:250 / 255.0 green:82 / 255.0 blue:82 / 255.0 alpha:1];
    _nothing.text = @"没有找到相关的主题";
    _nothing.textAlignment = NSTextAlignmentCenter;
    [self.tableView addSubview:_nothing];
    _nothing.hidden = YES;
    
    self.prompt = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 80)];
    _prompt.textColor = [UIColor colorWithRed:250/255.0 green:82/255.0 blue:82/255.0 alpha:1];
    _prompt.text = @"在搜索栏內输入主题相关的关键字搜索,便可得到相关商品主题,该关键字可与商品有关,也可与主题有关";
    _prompt.numberOfLines = 0;
    _prompt.textAlignment = NSTextAlignmentCenter;
    [self.tableView addSubview:_prompt];
    
    [self.tableView registerClass:[TopicTableViewCell class] forCellReuseIdentifier:@"search"];
    
    
    //    分界线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)backAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    QuanlityViewController *QVC = [[QuanlityViewController alloc] init];
    Topic *topic = [self.listArr objectAtIndex:indexPath.row];
    QVC.ID = topic.ID;
    [self.navigationController pushViewController:QVC animated:YES];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   return self.view.bounds.size.height / 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
    cell.backgroundColor = [UIColor clearColor];
    Topic *sea = [self.listArr objectAtIndex:indexPath.row];
    
    if ([sea.title containsString:_keyword]) {
        NSRange colorfulRange =[sea.title rangeOfString:_keyword];
        NSRange headRange = NSMakeRange(0, colorfulRange.location);
        NSRange commonRange = NSMakeRange(colorfulRange.length + colorfulRange.location, sea.title.length - colorfulRange.length - colorfulRange.location);
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:sea.title];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:colorfulRange];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:headRange];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:commonRange];
        cell.title.attributedText = str;
        
        
    }else{
        cell.title.text = sea.title;
    }
    [cell.pic sd_setImageWithURL:[NSURL URLWithString:sea.pic] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
    


    
    return cell;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.keyword = searchText;
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self handleData];
    _prompt.hidden = YES;
    [searchBar resignFirstResponder];
}

- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://open4.bantangapp.com/base/search/initData?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.3&os_versions=4.4.2&screensize=1080&v=6&keyword=%@", _keyword];
    [HandleData handleDataWithUrl:str completion:^(id data) {
        NSDictionary *bigDic = [data objectForKey:@"data"];
        self.listArr = [NSMutableArray array];
        NSArray *topicArr = [bigDic objectForKey:@"topic"];
        for (NSDictionary *dic in topicArr) {
            Topic *topic = [[Topic alloc] init];
            [topic setValuesForKeysWithDictionary:dic];
            [self.listArr addObject:topic];
            
        }
        
        [_tableView reloadData];
        if (_listArr.count == 0) {
            _nothing.hidden = NO;
            
        }else
        {
            _nothing.hidden = YES;
        }
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
